package huixue.cn.com.rxapp.rx;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import huixue.cn.com.rxapp.R;
import huixue.cn.com.rxapp.base.SimpleActivity;
import huixue.cn.com.rxapp.util.LogUtils;

public class SurfaceCameraActivity extends SimpleActivity
        implements SurfaceHolder.Callback,Camera.PreviewCallback{

    @BindView(R.id.btn1)
    Button btn1;
    @BindView(R.id.btn2)
    Button btn2;
    @BindView(R.id.btn3)
    Button btn3;

    @BindView(R.id.sur_camera)
    SurfaceView mSurfaceView;

    public SurfaceHolder mSurfaceHolder;

    private Camera mCamera;
    private Camera.Parameters mParameters;

    private int front = 0;
    private boolean isLight = false;

    @Override
    public int getLayout() {
        return R.layout.activity_surface_camera;
    }

    @Override
    public void initView() {

    }

    @Override
    public void addEvent() {

        //LogUtils.d("==addEvent=="+0%2);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        //将摄像头中的数据放置到SurfaceView中去呈现
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        initCamera(front);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mCamera.autoFocus((success,camera)->{
            if (success) {
                mParameters = mCamera.getParameters();
                //由于Android下摄像头预览数据只能  ImageFormat.NV21 格式的，所以解码时要经过一翻周折.
                mParameters.setPreviewFormat(ImageFormat.NV21);
                mParameters.setPictureFormat(PixelFormat.JPEG); //图片输出格式
                //mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);//预览持续发光
                if(front%2==0){
                    mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//持续对焦模式
                    isLight = false;
                }

                mCamera.setParameters(mParameters);
                mCamera.startPreview();
                mCamera.cancelAutoFocus();
            }
        });
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseCamera();
    }


    @OnClick({R.id.btn1,R.id.btn2,R.id.btn3})
    public void onViewClicked(View view) {

        if(view.getId()==R.id.btn1){
            PropertyValuesHolder p1 = PropertyValuesHolder.ofFloat("rotationY",0f,360,0f);
            PropertyValuesHolder p2 = PropertyValuesHolder.ofFloat("scaleX",1.0f,0.5f,1.0f);
            PropertyValuesHolder p3 = PropertyValuesHolder.ofFloat("scaleY",1.0f,0.5f,1.0f);

            ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(mSurfaceView,p1,p2,p3);
            objectAnimator.setDuration(5000).start();
        }else if(view.getId()==R.id.btn2){
            releaseCamera();
            front = (++front)%2;
            initCamera(front);
        }else if(view.getId()==R.id.btn3){
            mParameters = mCamera.getParameters();
            if(front%2==0 && !isLight){
                btn3.setText("关闭闪光灯");
                isLight = true;
                mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);//开启
            }else {
                btn3.setText("开启闪光灯");
                mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);//关闭
                isLight = false;
            }
            mCamera.setParameters(mParameters);

        }
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        Camera.Size size = camera.getParameters().getPreviewSize();
        try{
            YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
            if(image!=null){
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                image.compressToJpeg(new Rect(0, 0, size.width, size.height), 80, stream);
                Bitmap bmp = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
                stream.close();
            }
        }catch(Exception ex){
            Log.e("Sys","Error:"+ex.getMessage());
        }

    }


    private void releaseCamera(){
        if(mCamera!=null){
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    private void initCamera(int caremaId){
        try {
            // Open the Camera in preview mode
            mCamera = Camera.open(caremaId);
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewDisplay(mSurfaceHolder);
            mCamera.setPreviewCallback(this);
            mCamera.startPreview();
        } catch (IOException e) {

        }
    }

    @TargetApi(Build.VERSION_CODES.N)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void changeFlashLight(boolean openOrClose) {
        //判断API是否大于24（安卓7.0系统对应的API）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                //获取CameraManager
                CameraManager mCameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
                //获取当前手机所有摄像头设备ID
                String[] ids  = mCameraManager.getCameraIdList();
                for (String id : ids) {
                    CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);
                    //查询该摄像头组件是否包含闪光灯
                    Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                    Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
                    if (flashAvailable != null && flashAvailable
                            && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
                        //打开或关闭手电筒
                        mCameraManager.setTorchMode(id, openOrClose);
                    }
                }
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
    }

}
